# coding=utf-8
from pyquery import PyQuery
from export.distributors.b2b import B2b
from settings import db


class Fotos(B2b):
    host = 'http://fotos.ua/'
    mainUrl = 'http://fotos.ua/shop/'

    def __init__(self):
        B2b.__init__(self)

    def search(self, query):
        self.browser.open(self.host)
        self.browser.select_form(nr=0)
        self.browser['q'] = query
        self.handlerHtmlProduct(html=self.browser.get_data())

    def handlerHtmlCatalog(self, **kwargs):
        products = []
        if kwargs.has_key('url'):
            self.browser.open(kwargs['url'])
        else:
            self.browser.open(self.mainUrl)
        jQuery = PyQuery(self.browser.response().get_data())
        mainCategory = jQuery('.lc b a')
        definiteCategoryName_ = kwargs['definiteCategoryName']
        if isinstance(definiteCategoryName_, unicode):
            definiteCategoryName_ = definiteCategoryName_.encode('utf-8')
        definiteCategoryName = definiteCategoryName_.split('|')
        for category in mainCategory:
            categoryName = category.text
            if isinstance(categoryName, unicode):
                categoryName = categoryName.encode('utf-8')
            if unicode(categoryName, 'utf-8').lower() == unicode(definiteCategoryName[0], 'utf-8').lower():
                products_ = self.handlerHtmlCategory(url=category.attrib['href'],
                                                     definiteCategoryName=definiteCategoryName[1:])
                if products_:
                    products += products_
        return self.proccessRule({definiteCategoryName_: products})

    def handlerHtmlCategory(self, **kwargs):
        products = []
        url = kwargs['url']
        definiteCategoryName = kwargs['definiteCategoryName']
        self.browser.open(url)
        jQuery = PyQuery(self.browser.response().get_data())
        categories = jQuery('.lc b a')
        if categories:
            for category in categories:
                if definiteCategoryName:
                    categoryName = category.text
                    if isinstance(categoryName, unicode):
                        categoryName = categoryName.encode('utf-8')
                    if unicode(categoryName, 'utf-8').lower() == unicode(definiteCategoryName[0], 'utf-8').lower():
                        products_ = self.handlerHtmlCategory(url=category.attrib['href'],
                                                             definiteCategoryName=definiteCategoryName[1:])
                        if products_:
                            products += products_
                else:
                    products_ = self.handlerHtmlCategory(url=category.attrib['href'],
                                                         definiteCategoryName=None)
                    if products_:
                        products += products_
        productsLink = jQuery('.url a')
        for productLink in productsLink:
            product = self.handlerHtmlProduct(url=productLink.attrib['href'])
            if product:
                products.append(product)
        page = jQuery('.pa')
        nextPage = jQuery(page).next()
        if page and nextPage:
            products += self.handlerHtmlCategory(url=nextPage[0].attrib['href'], definiteCategoryName=None)
        return products

    def handlerHtmlProduct(self, **kwargs):
        product = {}
        url = kwargs['url']
        self.browser.open(url)
        jQuery = PyQuery(self.browser.response().get_data())
        product['name'] = jQuery(jQuery('.prodblock h3')[0]).text()
        descr = jQuery('.articl').text()
        if not descr:
            descr = product['name']
        product['descr'] = descr
        product['short_descr'] = descr[:100]
        product['price'] = jQuery(jQuery('.price')[0]).text().replace(' ', '').replace(u'грн.', '')
        sku = product['name'].split('(')
        if len(sku) == 1:
            return None
        if not self.checkProduct(sku, 1):
            return None
        product['sku'] = sku[len(sku) - 1].replace(')', '')
        url = jQuery('a[name=spac]')
        if not url:
            return None
        self.browser.open(url[0].attrib['href'])
        jQuery = PyQuery(self.browser.response().get_data())
        legend = jQuery('.legend')
        value = jQuery('.value')
        attrs = {}
        for i in range(len(legend)):
            attrs[legend[i].text] = value[i].text
        product['attrs'] = attrs
        return product

    def getProductSKUByName(self, name):
        result = db.sqlQuery('''SELECT value FROM magento.firstcatalog_product_entity_varchar where attribute_id=
                                (SELECT attribute_id FROM magento.firsteav_attribute where attribute_code='name'
                                and entity_type_id=4) and entity_id=;''')



